import Vue from 'vue';
import instance from './axios';
Vue.prototype.$http = instance;

class Http {
    constructor() {}
    getMethodType(method) {
        if(typeof method === 'string') {
            method = method.toUpperCase();
        }
        if(['PUT', 'POST','PATCH'].indexOf(method) != -1) {
            return 'data'
        } else {
            return 'params'
        }
    }
    ajax(method, url, params, headers, options) {
        const methodType = this.getMethodType(method)
        return instance({ 
            method, 
            url, 
            params: methodType === 'params' ? params : null, 
            data: methodType === 'data' ? params : null, 
            headers,
            ...options
        })
    }
}

export default new Http()

export class createHttp {
    constructor(url) {
        this.url = url;
        this.http = new Http()
    }

    add(params, headers) {
        return this.http.ajax('POST', this.url, params, headers)
    }

    update(params, headers) {
        return this.http.ajax('PUT', this.url, params, headers)
    }

    view(id, headers) {
        return this.http.ajax('GET', `${this.url}/${id}`, null, headers)
    }

    del(id, headers) {
        return this.http.ajax('DELETE', `${this.url}/${id}`, null, headers)
    }
}
